package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisMessageConstant;
import com.atguigu.service.OrderService;
import com.atguigu.utils.DateUtils;
import com.atguigu.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

/**
 * @program: meinian_parent
 * @author: Mr.Zhuo
 * @create: 2022-02-17 20:54
 **/
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    JedisPool jedisPool;
    @Reference
    OrderService orderService;

    @GetMapping("/findById")
    public Result findById(@RequestParam("id") Integer id) {
        try {
            Map map = orderService.findById(id);
            Date orderDateDB = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDateDB));
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.QUERY_ORDER_FAIL);
        }

    }

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        // 首先我们需要校验验证码是否正确
        String validateCode = (String) map.get("validateCode");

        // 然后获取手机号,获取到redis中的数据
        String telephone = (String) map.get("telephone");

        String redisCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        // 然后进去对比
        if (redisCode == null || !validateCode.equals(redisCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        // 然后直接进行数据order保存
        Result result = null;
        try {
            result = orderService.save(map);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return result;

        }


    }
}
